package com.zdsoft.blp.zongbuju.shouye.wuye.activity;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zdsoft.blp.R;
import com.zdsoft.blp.gongyong.API.API;
import com.zdsoft.blp.gongyong.camera.Camera;
import com.zdsoft.blp.gongyong.fanhui.FanHuiView;
import com.zdsoft.blp.gongyong.isLoginSuccess.IsLoginSuccess;
import com.zdsoft.blp.gongyong.net.BaseActivity;
import com.zdsoft.blp.gongyong.net.Net;
import com.zdsoft.blp.gongyong.net.NetCallback;
import com.zdsoft.blp.gongyong.net.UpLoadFiles;
import com.zdsoft.blp.zongbuju.shouye.wuye.adapter.GridAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/30.
 */
public class WYLiuYanActivity extends BaseActivity implements NetCallback {
    private FanHuiView back;
    private ImageView iv_xiangji, iv_chat, iv_chahao, iv_luyinDialog;
    private RelativeLayout rl_chat;
    private AnimationDrawable animationDrawable, luYinAnim;
    private GridView gv;
    private List<Bitmap> list;
    private GridAdapter adapter;
    private TextView tv_shuohua, tv_shijian;
    private int RECORD_AUDIO_REQUSET_CODE = 1;
    private static final int UPLOADFILE = 2;
    private MediaRecorder recorder;
    private File file;
    private RelativeLayout rl_luyin;
    private Long start, stop;
    private MediaPlayer player;
    private Button bt_baocun;
    private LinearLayout ll_luyinDialog;
    private EditText et_content;
    private String amrPath = null;

    @Override
    protected void init() {
        setContentView(R.layout.wy_wuyeliuyan);
        back = find(R.id.back);
        iv_xiangji = find(R.id.iv_xiangji);
        iv_chat = find(R.id.iv_chat);
        rl_chat = find(R.id.rl_chat);
        tv_shuohua = find(R.id.tv_shuohua);
        rl_luyin = find(R.id.rl_luyin);
        tv_shijian = find(R.id.tv_shijian);
        iv_chahao = find(R.id.iv_chahao);
        bt_baocun = find(R.id.bt_baocun);
        iv_luyinDialog = find(R.id.iv_luyinDialog);
        ll_luyinDialog = find(R.id.ll_luyinDialog);
        et_content = find(R.id.et_content);

        gv = find(R.id.gv);
        back.getTv_title().setText("物业留言");
        list = new ArrayList<>();
        adapter = new GridAdapter(list, getApplicationContext());
        gv.setAdapter(adapter);
        rl_luyin.setVisibility(View.INVISIBLE);

        rl_chat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_chat.setBackgroundResource(R.drawable.anima_chat);
                animationDrawable = (AnimationDrawable) iv_chat.getBackground();
                animationDrawable.start();
                player = new MediaPlayer();
                try {
                    player.setDataSource(Environment.getExternalStorageDirectory() + "/asd.amr");
                    player.prepare();
                    player.start();
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            try {
                                sleep(stop - start);
                                Message msg = handler.obtainMessage();
                                msg.what = 1;
                                handler.sendMessage(msg);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        iv_xiangji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Camera.setOnClickListener(iv_xiangji, WYLiuYanActivity.this);
            }
        });

        iv_chahao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rl_luyin.setVisibility(View.INVISIBLE);
            }
        });


        tv_shuohua.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (luYinAnim != null && luYinAnim.isRunning()) {
                        luYinAnim.stop();
                        iv_luyinDialog.setImageResource(R.drawable.v1);
                        ll_luyinDialog.setVisibility(View.GONE);
                    }
                    stop();
                    tv_shuohua.setText("按住 说话");
                    if (start != null && stop != null && stop > start) {
                        tv_shijian.setText((stop - start) / 1000 + "″");
                        amrPath = Environment.getExternalStorageDirectory() + "/asd.amr";
                        rl_luyin.setVisibility(View.VISIBLE);
                    } else {
                        rl_luyin.setVisibility(View.GONE);
                    }

                } else if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    ll_luyinDialog.setVisibility(View.VISIBLE);
                    iv_luyinDialog.setBackgroundResource(R.drawable.luyin_donghua);
                    luYinAnim = (AnimationDrawable) iv_luyinDialog.getBackground();
                    luYinAnim.start();
                   /* if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_DENIED) {
                        ActivityCompat.requestPermissions(WYLiuYanActivity.this, new String[]{android.Manifest.permission.RECORD_AUDIO}, RECORD_AUDIO_REQUSET_CODE);
                    } else {*/
                        tv_shuohua.setText("松开 结束");
                        start();
                    //}
                }
                return true;
            }
        });

        bt_baocun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpLoadFiles.upLoadFiles(list, handler, amrPath);
            }
        });

    }


    private void start() {
        if (recorder == null) {
            recorder = new MediaRecorder();
        }
        try {
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            file = new File(getSD(), "asd.amr");
            recorder.setOutputFile(file.getAbsolutePath());
            recorder.prepare();
            recorder.start();
            Date date = new Date();
            start = date.getTime();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void stop() {
        try {
            if (recorder != null) {
                recorder.setOnErrorListener(null);
                recorder.stop();
                Date date = new Date();
                stop = date.getTime();
                recorder.release();
                recorder = null;
            }
        } catch (Exception e) {
            recorder.reset();
            recorder = null;
            Toast.makeText(getApplicationContext(), "时间太短，无法录音", Toast.LENGTH_SHORT).show();
        }
    }

    public File getSD() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//判断sd卡是否挂载
            return Environment.getExternalStorageDirectory();
        } else {
            Toast.makeText(getApplicationContext(), "SD卡异常", Toast.LENGTH_SHORT).show();
            return null;
        }
    }

    public void stopFrame() {

        if (animationDrawable != null && animationDrawable.isRunning()) { //如果正在运行,就停止

            animationDrawable.stop();
            iv_chat.setBackgroundResource(R.drawable.chatfrom_voice_playing_f3);

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Camera.dialog.dismiss();
        switch (requestCode) {
            case Camera.PAI:
                if (resultCode != RESULT_CANCELED) {
                    try {
                        FileInputStream in = new FileInputStream(Environment.getExternalStorageDirectory() + "/image.jpg");
                        Bitmap bitmap = BitmapFactory.decodeStream(in);
                        list.add(bitmap);
                        adapter.notifyDataSetChanged();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                }
                break;
            case Camera.XUAN:
                if (resultCode != RESULT_CANCELED) {
                    ContentResolver resolver = getContentResolver();
                    InputStream in = null;
                    try {
                        in = resolver.openInputStream(data.getData());
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    Bitmap bitmap = BitmapFactory.decodeStream(in);
                    list.add(bitmap);
                    adapter.notifyDataSetChanged();
                }
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == RECORD_AUDIO_REQUSET_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                start();
            }
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                stopFrame();
            }
            if (msg.what == 2) {
                if (!"".equals(msg.obj.toString())) {
                    upLoadImage(msg.obj.toString());
                }
            }
        }
    };

    private void upLoadImage(String fileIds) {
        SharedPreferences sp = getSharedPreferences("info", Context.MODE_PRIVATE);
        String userId = sp.getString("userId", "");
        if (!"".equals(userId) && !"".equals(fileIds)) {
            Net net = new Net();
            net.url = API.PROBLEM_URL;
            net.nameSpace = API.PROBLEM_NAMESPACE;
            net.methodName = API.PROPERTYFEEDBACKSAVE;
            Map<String, Object> map = new HashMap<>();
            map.put("title", "");
            map.put("content", et_content.getText().toString());
            map.put("contact", "");
            map.put("contactPhone", "");
            map.put("communityCode", sp.getString("communityCode", "00001"));
            map.put("tempFileIds", fileIds);
            if (amrPath != null) {
                map.put("vflength", (stop - start) / 1000 + "");
            } else {
                map.put("vflength", "");
            }
            map.put("userId", userId);
            net.parms = map;
            getServer(net, WYLiuYanActivity.this);
        }
    }

    @Override
    public void onResponse(boolean flag, int code, String res) {
        if (flag) {
            try {
                JSONObject object = new JSONObject(res);
                Toast.makeText(getApplicationContext(), object.getString("msg"), Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}
